package handler

import (
	"art-man-sys/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func AddArticle(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "添加失败,字段不能为空",
		})
		return
	}
	article := models.Article{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&article).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

}
func Upload(c *gin.Context) {
	file, _ := c.FormFile("img")
	if file == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "上传失败,上传内容不能为空",
		})
		return
	}
	if file.Size > 2*1024*1024 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "图片不能超过2M",
		})
		return
	}
	path := "static/img/" + file.Filename
	err := c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "上传失败",
		})
		return
	}
	url := "http://" + c.Request.Host + "/" + path
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": url,
	})
	return
}
func DeleteArticle(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var article models.Article
	err := models.DB.Where("id = ?", id).First(&article).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "内容不存在",
		})
		return
	}
	err = models.DB.Where("id = ?", id).Delete(&article).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func ArticleList(c *gin.Context) {
	var article []models.Article
	err := models.DB.Find(&article).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "列表获取失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": article,
	})
	return
}
